package com.cne.gmail.Gmail.controller;


import com.cne.gmail.Gmail.dao.MailSendInfoRepository;
import com.cne.gmail.Gmail.dao.MessageRepository;
import com.cne.gmail.Gmail.imp.SendEmailService;
import com.cne.gmail.Gmail.model.MailSenderInfo;
import com.cne.gmail.Gmail.model.MessageModel;
import com.cne.gmail.Gmail.response.GmailServiceResponse;
import com.cne.gmail.Gmail.service.BackendService;
import com.cne.gmail.Gmail.service.GmailService;
import com.cne.gmail.Gmail.service.UserService;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Optional;


@Log4j2
@RestController
@RequestMapping("gmail")
@Api(description ="已删除邮箱和草稿箱管理")
public class TrashAndDraftController {
    @Autowired
    BackendService backendService;
    @Autowired
    MessageRepository messageRepository;
    @Autowired
    MailSendInfoRepository mailSendInfoRepository;
    private final String USERID="me";
    @Autowired
    GmailService gmailService;
    @Autowired
    UserService userService;
    @ApiOperation(value = "分页查询已删除邮件",notes = "分页查询已删除邮件")
    @GetMapping("alreadyDelete")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "label",value = "邮箱类型",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "emailAddress",value = "邮箱地址",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "currentPage",value = "当前页码",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "pageSize",value = "每页多少条",required = true,dataType = "String")
    })
    public GmailServiceResponse alreadyDelete(@RequestParam String emailAddress, @RequestParam String label, @RequestParam String currentPage, @RequestParam String pageSize){
        GmailServiceResponse response=new GmailServiceResponse();
        Page<MessageModel> messageModels = backendService.selectMessagePage(Integer.valueOf(currentPage), Integer.valueOf(pageSize), emailAddress, label);
        if (messageModels.getContent().size()!=0){
            response.setCode(200);
            response.setData(messageModels);
            return response;
        }else {
            response.setMsg("已删除邮件为空");
            return response;
        }
    }

    /**
     * 已删除邮件恢复到收件箱
     * @param emailAddress
     * @param messageId
     * @return
     */
    @ApiOperation(value = "恢复到收件箱",notes = "恢复到收件箱")
    @PostMapping("restore")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "emailAddress",value = "邮箱地址",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "messageId",value = "邮件Id",required = true,dataType = "String"),
    })
    public GmailServiceResponse restore(@RequestParam String emailAddress, @RequestParam String messageId) {
        GmailServiceResponse response=new GmailServiceResponse();
        try {
            MessageModel result=messageRepository.findByEmailAddressAndMessageId(emailAddress,messageId);
            if (result==null){
                response.setMsg("恢复失败");
                return  response;
            }else {
                MessageModel message=(MessageModel) result.clone();
                message.setLabel("INBOX");
                messageRepository.save(message);
                response.setMsg("已恢复到收件箱，请及时查看");
                return response;
            }

        }catch (Exception e){
            response.setMsg("恢复失败");
            log.info(e.getMessage());
            return  response;
        }
    }
    /**
     * 彻底删除邮件
     * @param messageIds
     * @return
     */
    @ApiOperation(value = "彻底删除邮件",notes = "恢复到收件箱")
    @PostMapping("delete")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "messageId",value = "邮件Id",required = true,dataType = "String")
    })
    public GmailServiceResponse delete( @RequestParam List<String> messageIds) {
        GmailServiceResponse response=new GmailServiceResponse();
        try {
            for (String id:messageIds)  messageRepository.deleteById(id);
            response.setMsg("删除成功");
            response.setCode(200);
            return response;
        }catch (Exception e){
            log.info(e.getMessage());
            response.setMsg("未删除成功");
            return response;
        }
    }


    /**
     * 创建草稿箱
     * @param data
     * @return
     */
    @PostMapping("createDreft")
    @ApiOperation(value = "创建草稿箱",notes = "创建草稿箱")
    public GmailServiceResponse createDraft(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) MailSenderInfo data){
        GmailServiceResponse response = new GmailServiceResponse();
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            data.setCDate(simpleDateFormat.format(System.currentTimeMillis()));
            MailSenderInfo mailSenderInfo = mailSendInfoRepository.insert(data);
            response.setCode(200);
            response.setData(mailSenderInfo);
            response.setMsg("创建草稿箱成功");
            return response;
        } catch (Exception e) {
            log.info(e.getMessage());
            response.setMsg("创建草稿箱失败");
            return response;
        }
    }

    /**
     * 更新草稿箱
     * @param data
     * @return
     */
    @PostMapping("updateDraft")
    @ApiOperation(value = "更新草稿箱信息",notes = "更新草稿箱")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "draftId",value = "草稿箱唯一id",required = true,dataType = "String"),
    })
    public GmailServiceResponse updateDraft(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) MailSenderInfo data,@RequestParam String draftId){
        GmailServiceResponse response = new GmailServiceResponse();
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            data.setCDate(simpleDateFormat.format(System.currentTimeMillis()));
            data.setId(draftId);
            mailSendInfoRepository.save(data);
            response.setCode(200);
            response.setData(data);
            response.setMsg("更新草稿箱完成");
            return response;
        } catch (Exception e) {
            log.info(e.getMessage());
            response.setMsg("更新草稿箱失败");
            return response;
        }
    }

    /**
     * 用草稿箱发送邮件
     * @param emailAddress
     * @param id
     * @return
     */
    @PostMapping("sendByDraft")
    @ApiOperation(value = "根据草稿箱发送邮件",notes = "根据草稿箱发送邮件")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(paramType = "query", name = "emailAddress", value = "邮箱地址", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "id", value = "草稿箱唯一id", required = true, dataType = "String")
    })
    public GmailServiceResponse sendByDraft(@RequestParam String emailAddress,@RequestParam String id) {
        GmailServiceResponse response = new GmailServiceResponse();
        SendEmailService sendEmailService = new SendEmailService();
        Optional<MailSenderInfo> result = mailSendInfoRepository.findById(id);
        if (result.get() == null) {
            response.setMsg("草稿箱信息未找到，请先添加到数据库，或联系开发人员");
            return response;
        } else {
            response = sendEmailService.send(userService, emailAddress, result.get(), USERID, gmailService, backendService);
            mailSendInfoRepository.deleteById(id);
            return response;
        }
    }
    /**
     * 删除草稿箱
     * @param ids
     * @return
     */
    @PostMapping("deleteDraft")
    @ApiOperation(value = "根据草稿箱发送邮件",notes = "根据草稿箱发送邮件")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(paramType = "query", name = "ids", value = "草稿箱唯id", required = true, dataType = "String")
    })
    public GmailServiceResponse deleteDraft(@RequestParam List<String> ids) {
        GmailServiceResponse response = new GmailServiceResponse();
        try {
            for (String id:ids) mailSendInfoRepository.deleteById(id);
            response.setMsg("删除成功");
            response.setCode(200);
            return  response;
        }catch (Exception e){
            response.setMsg("删除失败");
            log.info(e.getMessage());
            return response;
        }
    }
    @PostMapping("searchDraft")
    @ApiOperation(value = "分页查询草稿箱",notes = "分页查询草稿箱")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(paramType = "query", name = "emailAddress", value = "邮箱地址", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "currentPage",value = "当前页码",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "pageSize",value = "每页多少条",required = true,dataType = "String")
    })
    public GmailServiceResponse searchDraft(@RequestParam String emailAddress,@RequestParam String currentPage,@RequestParam String pageSize) {
        GmailServiceResponse response = new GmailServiceResponse();
        Sort sort = new Sort(Sort.Direction.DESC, "data");
        Pageable page = new PageRequest(Integer.valueOf(currentPage), Integer.valueOf(pageSize), sort);
        Page<MailSenderInfo> result = mailSendInfoRepository.findByFrom(emailAddress, page);
        if (result.getContent().size()==0){
            response.setMsg("当前用户草稿箱为空，请先添加");
            return response;
        }else {
            response.setData(result);
            response.setCode(200);
            return response;
        }
    }

}
